package com.example.imageloader.impl;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.widget.ImageView;

import com.example.imageloader.IImageLoader;
import com.example.imageloader.common.ImageOptions;
import com.example.imageloader.common.PicassoTrans;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;

import java.io.File;
import java.lang.ref.SoftReference;

public class PicassoImpl implements IImageLoader {

    @Override
    public void loadFileIntoImageView(Context context, File file, ImageView target, ImageOptions options) {
        loaderImageView(context,file,target,options);
    }

    @Override
    public void loadResourceIntoImageView(Context context, int source, ImageView target, ImageOptions options) {
        loaderImageView(context,source,target,options);
    }

    @Override
    public void loadByteArrayIntoImageView(Context context, byte[] bytes, ImageView target, ImageOptions options) {
        throw new IllegalStateException("没有提供这个方法");
    }

    @Override
    public void loadUriIntoImageView(Context context, Uri uri, ImageView target, ImageOptions options) {
        loaderImageView(context,uri,target,options);
    }

    @Override
    public void loadIntoImageView(Context context, String url, ImageView target, ImageOptions options) {
        loaderImageView(context,url,target,options);
    }

    private void loaderImageView(Context context,Object source,ImageView target,ImageOptions options){
        SoftReference<Context> ctx = new SoftReference<>(context);
        RequestCreator build;
        if (source instanceof File){
            build = Picasso.with(ctx.get()).load((File) source);
        }else if (source instanceof Integer){
            build = Picasso.with(ctx.get()).load((int) source);
        }else if (source instanceof Uri){
            build = Picasso.with(ctx.get()).load((Uri) source);
        }else if (source instanceof String){
            build = Picasso.with(ctx.get()).load((String) source);
        }else {
            throw new IllegalStateException("没有这个资源加载方法");
        }
        setBuilderOptions(build,options);
        build.into(target);
    }

    private void setBuilderOptions(RequestCreator builder,ImageOptions options){
        if (options != null){
            return;
        }
        if (options.getPlaceImage()!= 0){
            builder.placeholder(options.getPlaceImage());
        }
        if (options.getErrorImage()!= 0){
            builder.error(options.getErrorImage());
        }
        if (options.getImageSize() != null){
            int[] imageSize = options.getImageSize();
            builder.resize(imageSize[0],imageSize[1]);
        }
        if (options.isSkipMemoryCache()){
            builder.memoryPolicy(MemoryPolicy.NO_CACHE);
        }

    }
}
